package com.wolfalpha.utron.activity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.wolfalpha.utron.R;
import com.wolfalpha.utron.activity.base.BaseNormal3Activity;
import com.wolfalpha.utron.service.FileService;
import com.wolfalpha.utron.service.PartnerService;
import com.wolfalpha.utron.service.impl.FileServiceImpl;
import com.wolfalpha.utron.service.impl.PartnerServiceImpl;
import com.wolfalpha.utron.ui.UIHelper;
import com.wolfalpha.utron.utils.FileUtils;
import com.wolfalpha.utron.utils.ThreadPoolUtils;
import com.wolfalpha.utron.view.ListAlertDialog;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * 升级页面
 * <p/>
 * Created by luodon on 15/9/2.
 */
public class PartnerToAuthActivity extends BaseNormal3Activity implements View.OnClickListener {
    private EditText tvYX;          //院系
    private TextView tvNJ;          //年级

    private ImageView ivPic;        //认证照片

    private final int UPDATE_SUCCESS = 1;
    private final int UPDATE_FAIL = 2;

    private ProgressDialog pd;

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            switch (msg.what) {
                case UPDATE_SUCCESS:
                    finish();
                    break;
                case UPDATE_FAIL:
                    UIHelper.ToastMessage(PartnerToAuthActivity.this, "更新失败,请重试");
                    break;
            }
        }
    };

    private PartnerService partnerService;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_partner_edit_to_auth);
        fileService = new FileServiceImpl();
        partnerService = new PartnerServiceImpl();

        initView();
        initListeners();

    }

    /**
     * 初始化界面
     */
    private void initView() {
        setTvTitle("合伙人认证");
        ivPic = (ImageView) findViewById(R.id.iv_partner_edit_to_auth_photo);

        tvYX = (EditText) findViewById(R.id.et_partner_edit_to_auth_school);
        tvNJ = (TextView) findViewById(R.id.tv_partner_edit_to_auth_group);

        pd = new ProgressDialog(PartnerToAuthActivity.this);
        pd.setMessage("正在上传数据...");
    }

    /**
     * 初始化监听
     */
    private void initListeners() {
        tvNJ.setOnClickListener(this);

        ivPic.setOnClickListener(this);
    }

    private String nj = "";
    private String yx = "";
    private String pic = "";

    /**
     * 选择年级
     */
    private void showNjs() {
        final ListAlertDialog ad = new ListAlertDialog(PartnerToAuthActivity.this);
        ad.setTitle("选择您的年级");
        final String[] arr = this.getResources().getStringArray(R.array.partner_group);
        ad.setArray(arr);
        ad.setOnFinishedListener(new ListAlertDialog.OnFinishedListener() {
            @Override
            public void finish(int input) {
                tvNJ.setText(arr[input]);
                nj = arr[input];
            }
        });
    }

    @Override
    public void rightOperation() {
        if (TextUtils.isEmpty(yx = tvYX.getText().toString().trim()) || TextUtils.isEmpty(nj)) {
            UIHelper.ToastMessage(PartnerToAuthActivity.this, "信息不完整，请求失败");
            return;
        }
        if (TextUtils.isEmpty(pic)) {
            UIHelper.ToastMessage(PartnerToAuthActivity.this, "请上传认证照片");
            return;
        }
        pd.show();
        ThreadPoolUtils.execute(new Runnable() {
            @Override
            public void run() {
                boolean result = partnerService.uptoAuthPartner(yx, nj, pic);
                handler.sendEmptyMessage(result ? UPDATE_SUCCESS : UPDATE_FAIL);
                pd.dismiss();
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_partner_edit_to_auth_group:
                showNjs();
                break;
            case R.id.iv_partner_edit_to_auth_photo:
                showPickPhoto();
                break;
        }
    }

    private File f = null;
    private FileService fileService = null;

    private static final int IMAGE_REQUEST_CODE = 0;
    private static final int CAMERA_REQUEST_CODE = 1;
    private static final int RESIZE_REQUEST_CODE = 2;

    private static final String IMAGE_FILE_NAME = "utron/imageCache/partner_auth.jpg";//头像拍照路径

    /**
     * 选召唤类型
     */
    private void showPickPhoto() {
        final ListAlertDialog ad = new ListAlertDialog(PartnerToAuthActivity.this);
        ad.setTitle("选择项目目前的阶段");
        final String[] arr = new String[]{"本地上传", "拍照"};
        ad.setArray(arr);
        ad.setOnFinishedListener(new ListAlertDialog.OnFinishedListener() {
            @Override
            public void finish(int input) {
                if (input == 0) {
                    //本地上传
                    Intent galleryIntent = new Intent(Intent.ACTION_GET_CONTENT);
                    galleryIntent.addCategory(Intent.CATEGORY_OPENABLE);
                    galleryIntent.setType("image/*");
                    startActivityForResult(galleryIntent, IMAGE_REQUEST_CODE);
                }
                if (input == 1) {
                    //拍照上传
                    if (FileUtils.checkSDExists()) {
                        Intent cameraIntent = new Intent(
                                "android.media.action.IMAGE_CAPTURE");
                        cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, getImageUri());
                        cameraIntent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 0);
                        startActivityForResult(cameraIntent, CAMERA_REQUEST_CODE);
                    } else {
                        UIHelper.ToastMessage(PartnerToAuthActivity.this, "请先插入SD卡");
                    }
                }
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != RESULT_OK) {
            return;
        } else {
            switch (requestCode) {
                case IMAGE_REQUEST_CODE:
                    resizeImage(data.getData());
                    break;
                case CAMERA_REQUEST_CODE:
                    if (FileUtils.checkSDExists()) {
                        resizeImage(getImageUri());
                    } else {
                        UIHelper.ToastMessage(PartnerToAuthActivity.this, "没有存储卡");
                    }
                    break;

                case RESIZE_REQUEST_CODE:
                    if (data != null) {
                        showResizeImage(data);
                    }
                    break;
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    /**
     * 显示头像图片
     *
     * @param data
     */
    private void showResizeImage(Intent data) {
        Bundle extras = data.getExtras();
        if (extras != null) {
            Bitmap photo = null;
            try {
                photo = BitmapFactory.decodeStream(getContentResolver().openInputStream(getImageUri()));
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                return;
            }
            try {
                f = getImage();
                FileOutputStream fOut = null;
                try {
                    fOut = new FileOutputStream(f);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
                photo.compress(Bitmap.CompressFormat.JPEG, 100, fOut);
                fOut.flush();
                fOut.close();
                if (f != null) {
                    ThreadPoolUtils.execute(new Runnable() {
                        @Override
                        public void run() {
                            String res = fileService.uploadBig(f);
                            if (res != null) {
                                System.out.println(res);
                                pic = res;
                            } else {
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        UIHelper.ToastMessage(PartnerToAuthActivity.this, "上传LOGO失败");
                                    }
                                });
                            }
                        }
                    });
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            ivPic.setImageBitmap(photo);
        }
    }

    /**
     * 对图片进行裁剪
     *
     * @param uri
     */

    public void resizeImage(Uri uri) {
        try {
            Intent intent = new Intent("com.android.camera.action.CROP");
            intent.setDataAndType(uri, "image/*");
            intent.putExtra("crop", "true");
            intent.putExtra("aspectX", 1);
            intent.putExtra("aspectY", 1);
            intent.putExtra("outputX", 400);
            intent.putExtra("outputY", 400);
            intent.putExtra("scale", true);
            intent.putExtra("output", getImageUri());  // 传入目标文件
            intent.putExtra("return-data", false);
            intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString()); //输入文件格式
            intent.putExtra("noFaceDetection", true); // no face detection
            startActivityForResult(intent, RESIZE_REQUEST_CODE);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取图片内容
     *
     * @return
     */
    private File getImage() {
        return new File(Environment.getExternalStorageDirectory(),
                IMAGE_FILE_NAME);
    }

    /**
     * 获取图像地址
     *
     * @return
     */
    private Uri getImageUri() {
        return Uri.fromFile(new File(Environment.getExternalStorageDirectory(),
                IMAGE_FILE_NAME));
    }
}
